package zkrt.cc.fishelevatorservice.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import zkrt.cc.fishelevatorservice.common.R;
import zkrt.cc.fishelevatorservice.common.ResultCode;


import java.util.stream.Collectors;

/**
 * @author xulinyu
 */
@ControllerAdvice
public class WebExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(WebExceptionHandler.class);

    public WebExceptionHandler() {
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public R<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数校验异常：RuntimeException:{}, error:{}", e, e.getMessage());
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage).sorted().collect(Collectors.joining(","));
        return R.fail(ResultCode.PARAM_VALID_ERROR,message);
    }

    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public R<String> handleException(RuntimeException e) {
        //打印出报错的堆栈跟踪信息
        log.error("系统异常信息：RuntimeException:{}, error:{}", e, e.getMessage(),e);
        return R.fail(ResultCode.INTERNAL_SERVER_ERROR,e.getMessage());
    }
}
